<template>
  <div class="news-list">
    <div class="news-list-header">
      <div class="news-list-header-left">
        <el-input placeholder="请输入关键字" v-model="selectNewsname" />
        <el-button type="primary" @click="selectNews"><el-icon>
            <Search />
          </el-icon>查询</el-button>
      </div>
      <div class="news-list-header-right">
        <el-input placeholder="在本页检索" v-model="search" />
      </div>
    </div>
    <div class="news-list-table">
      <el-table :data="filterTableData" :border="false" :height="tableHeight" style="width: 100%" tooltip-effect>
        <el-table-column type="expand">
          <template #default="props">
            <div m="4" class="table-expand">
              <b>新闻标题: </b>
              <p m="t-0 b-2">{{ props.row.newsTitle }}</p>
              <b>新闻描述: </b>
              <p m="t-0 b-2">{{ props.row.newsDesc }}</p>
              <b>新闻内容: </b>
              <p m="t-0 b-2">{{ props.row.newsContent }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" prop="newsDate" align="center" />
        <el-table-column label="新闻标题" prop="newsTitle" align="center" show-overflow-tooltip />
        <el-table-column label="新闻栏目" prop="categoryName" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"><el-icon>
                <EditPen />
              </el-icon></el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)"><el-icon>
                <Delete />
              </el-icon></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="news-list-footer">
      <el-pagination small background layout="total, prev, pager, next" :pager-count="5" :total="totals"
        @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogFormVisible" title="编辑新闻">
      <el-form :model="form">
        <el-form-item label="新闻标题：">
          <el-input v-model="form.newsTitle" />
        </el-form-item>
        <el-form-item label="新闻描述：">
          <el-input v-model="form.newsDesc" type="textarea" style="overflow-y: auto" />
        </el-form-item>
        <el-form-item label="新闻内容：">
          <el-input v-model="form.newsContent" type="textarea" style="overflow-y: auto" />
        </el-form-item>
        <el-form-item label="新闻属性：">
          <el-checkbox v-model="form.newsIsCheck">是否校验</el-checkbox>
          <el-checkbox v-model="form.newsIsTop">是否置顶</el-checkbox>
          <el-checkbox v-model="form.newsIsRot">是否为热点新闻</el-checkbox>
          <el-checkbox v-model="form.newsIsRecommend">是否为推荐新闻</el-checkbox>
        </el-form-item>
        <el-form-item label="新闻栏目：" prop="categoryName">
          <el-select v-model="categoryName" class="m-2" placeholder="新闻栏目">
            <el-option v-for="item in option" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片/视频：">
          <el-upload v-model:file-list="fileList" action="/path/common/upload" multiple :before-remove="beforeRemove"
            :on-preview="handlePreview" :on-success="uploadsuccess" :on-exceed="handleExceed" :limit="1">
            <el-button type="primary"><el-icon>
                <Refresh />
              </el-icon>点击更换</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="UpdataNews">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible">
      <el-image v-if="!showurl" style="width: 600px; height: 400px" :src="dialogImageUrl" fit="scale-down" />
      <video :src="dialogImageUrl" v-if="showurl" :width="600" :height="400" controls></video>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../../api/api'
import { Delete, EditPen, Search, Refresh } from '@element-plus/icons-vue'
import type { UploadUserFile, UploadProps } from 'element-plus'

const totals = ref(0)

let tableHeight = ref(window.innerHeight - 236)

const tableData = ref<any[]>([])

const selectNewsname = ref('')
const search = ref('')
const currentpage = ref(0)

const dialogFormVisible = ref(false)
const dialogVisible = ref(false)

const categoryName = ref<any>()

const option = ref<any[]>([])

const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')

const showurl = ref(false)

const form = reactive({
  newsTitle: '',
  newsDesc: '',
  newsContent: '',
  newsCount: 0,
  newsImagePath: '',
  newsIsCheck: false,
  newsIsTop: false,
  newsIsRot: false,
  newsIsRecommend: false,
  newsClassification: '图片新闻',
  categoryId: 0,
  newsId: ''
})

const handleEdit = (index: any, row: any) => {
  dialogFormVisible.value = true
  fileList.value.pop()
  form.newsId = row.newsId
  form.newsTitle = row.newsTitle
  form.newsIsTop = row.newsIsTop
  form.newsIsRot = row.newsIsRot
  form.newsIsRecommend = row.newsIsRecommend
  form.newsIsCheck = row.newsIsCheck
  form.newsImagePath = row.newsImagePath
  form.newsDesc = row.newsDesc
  form.newsCount = row.newsCount
  form.newsContent = row.newsContent
  form.newsClassification = row.newsClassification

  categoryName.value = row.categoryName

  const file = {
    name: getfilename(decodeURI(form.newsImagePath)),
    url: form.newsImagePath
  }
  fileList.value.push(file)
}

const uploadsuccess: UploadProps['onSuccess'] = (response) => {
  ElMessage({
    message: '上传成功！',
    type: 'success',
  })
  fileList.value.pop()
  dialogImageUrl.value = response.data
  const file = {
    name: getfilename(decodeURI(response.data)),
    url: response.data
  }
  fileList.value.push(file)
}


const handlePreview: UploadProps['onPreview'] = (uploadFile: any) => {
  dialogVisible.value = true
  dialogImageUrl.value = uploadFile.url as string
  if (uploadFile.name.split('.')[1] == 'mp4') {
    showurl.value = true
  } else {
    showurl.value = false
  }
}

const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning(
    `限制更换的文件为 1 个`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
  return ElMessageBox.confirm(
    `确认要删除 ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const handleDelete = (index: any, row: any) => {
  ElMessageBox.confirm(
    `你确认要删除第${index + 1}条新闻吗？`,
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      api.DeleteNews({ newsIds: row.newsId })
        .then(res => {
          if (res.data.code == 200) {
            ElMessage({
              message: '删除新闻成功',
              type: 'success'
            })
            handleCurrentChange(currentpage.value)
          }
        }).catch(err => console.log(err))
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    })
}

// 更新逻辑功能
const UpdataNews = () => {
  dialogFormVisible.value = false

  option.value.forEach((item) => {
    if (item.categoryId == categoryName.value || categoryName.value == item.categoryName) {
      form.categoryId = item.categoryId
    }
  })

  form.newsImagePath = fileList.value[0].url as string

  api.UpdateNews(form)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage({
          message: '修改新闻成功',
          type: 'success'
        })
        handleCurrentChange(currentpage.value)
      }
    }).catch(err => console.log(err))
  console.log(form);
}


const selectNews = () => {
  api.selectNews({ page: 1, size: 10, name: selectNewsname.value })
    .then(res => {
      if (res.data.code == 200) {
        ElMessage({
          message: '查询新闻成功',
          type: 'success'
        })
        tableData.value = res.data.data.records
      }
    }).catch(err => console.log(err))
}



const initNews = (current: number) => {
  api.selectNews({ page: current, size: 10 })
    .then(res => {
      if (res.data.code == 200) {
        tableData.value = res.data.data.records
        totals.value = res.data.data.total
      }
    })
    .catch(err => console.log(err))
}



const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.newsTitle.toLowerCase().includes(search.value.toLowerCase())
  )
)


const getfilename = (url: string) => {
  if (url != '') {
    return url.split('/')[4].split('?')[0]
  }
  return ''
}


const handleCurrentChange = (val: number) => {
  currentpage.value = val
  initNews(val)
}


onMounted(() => {

  handleCurrentChange(1)

  api.selectallcategory()
    .then(res => {
      if (res.data.code == 200) {
        option.value = res.data.data
      }
    }).catch(err => console.log(err))

  window.onresize = () => {
    tableHeight.value = window.innerHeight - 236
  }
})

</script>

<style scoped>
.news-list-header {
  display: flex;
  padding: 10px;
  justify-content: space-between;
  align-items: center;
}

.news-list-header-left {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  align-items: center;
}

.news-list-header-left button {
  margin-left: 15px;
}

.news-list-header-right {
  padding: 10px;
}

.news-list {
  background-color: #fcfffc;
  border-radius: 10px;
}

.news-list-footer {
  display: flex;
  justify-content: center;
  padding: 10px;
}

.news-list-table {
  box-sizing: border-box;
  height: calc(100% - 3rem);
}

.table-expand {
  padding: 10px;
}
</style>